package com.solution.wx.my.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.solution.admin.customer.entity.CompanyEntity;
import com.solution.admin.customer.entity.CustomerEntity;
import com.solution.admin.customer.service.CustomerService;
import com.solution.admin.home.service.RedisService;
import com.solution.common.config.PublicConfig;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.utils.ip.IPUtils;
import com.solution.common.utils.string.StringUtil;
import com.solution.wx.core.constants.WechatConstants;
import com.solution.wx.core.entity.SNSUserEntity;
import com.solution.wx.core.util.WechatUtil;
import com.solution.wx.my.constants.MyConstants;

/**
 * 个人设置控制层
 * @author: solin
 * @date: 2017年11月22日 下午2:21:21
 */
@RequestMapping("/wx/my/setting")
@Controller("wxSettingController")
public class SettingController extends BaseController{
	private Logger logger = LoggerFactory.getLogger(SettingController.class);
	@Autowired
	RedisService redisService;
	@Autowired
	CustomerService customerService;
	
	/**
	 * 跳转到个人设置页面
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月22日 下午2:32:18
	 */
	@RequestMapping("")
	public String toSettingPage(HttpServletRequest request) {
		//从cookie中获取openId
		String openId = WechatUtil.getOpenIdFromCookie(request);
		//从redis中获取通过网页授权获取的用户信息
		String strSNSUserInfoJson = redisService.get(WechatConstants.SNS_USERINFO_KEY.concat(openId));
		SNSUserEntity snsUserInfo = JSONObject.parseObject(strSNSUserInfoJson, SNSUserEntity.class);
		//获取客户信息
		Long CustomerId = this.getCustomerId();
		CustomerEntity customerInfo = customerService.getCustomerById(CustomerId);
		request.setAttribute("customerInfo", customerInfo);
		//客户头像
		String headImageUrl = "";
		if (StringUtil.isEmpty(customerInfo.getHeadImage())) {
			headImageUrl = snsUserInfo.getHeadImgUrl();
		} else {
			headImageUrl = PublicConfig.IMG_ROOT_URL.concat(customerInfo.getHeadImage());
		}
		request.setAttribute("headImageUrl", headImageUrl);
		//客户等级
		CompanyEntity companyInfo = this.getCompany();
		request.setAttribute("customerType", companyInfo.getCustomerLevelInfo().getLevelName());
		
		//调用JSAPI必须的参数
		String jsapi_ticket = WechatUtil.getJspiTicket();
		String url = request.getRequestURL().toString();
		String urlParam = request.getQueryString();
		if (StringUtil.isNotNull(urlParam)) {
			url = url + "?" + urlParam;
		}
		Map<String, String> sign = WechatUtil.sign(jsapi_ticket, url);
		request.setAttribute("appId", WechatUtil.APPID);
		request.setAttribute("timestamp", sign.get("timestamp"));
		request.setAttribute("nonceStr", sign.get("nonceStr"));
		request.setAttribute("signature", sign.get("signature"));
		
		System.out.println("###########################################");
		System.out.println("jsapi_ticket:" + jsapi_ticket);
		System.out.println("url:" + url);
		System.out.println("noncestr:" + sign.get("nonceStr"));
		System.out.println("timestamp:" + sign.get("timestamp"));
		System.out.println("signature:" + sign.get("signature"));
		System.out.println("###########################################");
		
		return "/wx/my/setting/setting";
	}
	
	/**
	 * 跳转到修改登录密码页面
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月23日 下午4:56:42
	 */
	@RequestMapping("toResetPasswordPage")
	public String toResetPasswordPage(HttpServletRequest request) {
		CustomerEntity customerInfo = this.getCustomer();
		request.setAttribute("mobile", customerInfo.getMobile());
		return "/wx/my/setting/resetPwd";
	}
	
	/**
	 * 跳转到设置邮箱页面
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月23日 下午5:03:17
	 */
	@RequestMapping("toSetEmailPage")
	public String toSetEmailPage(HttpServletRequest request, String email) {
		request.setAttribute("email", email);
		return "/wx/my/setting/setEmail";
	}
	
	/**
	 * 跳转到设置QQ页面
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月23日 下午5:03:20
	 */
	@RequestMapping("toSetQQPage")
	public String toSetQQPage(HttpServletRequest request, String qqNumber) {
		request.setAttribute("qqNumber", qqNumber);
		return "/wx/my/setting/setQQ";
	}
	
	/**
	 * 重置密码
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月24日 上午10:13:42
	 */
	@RequestMapping("resetPassword")
	public String resetPassword(HttpServletRequest request, Model model, String password, String receiveVerifyCode) {
		String mobile = request.getParameter("mobile");
		model.addAttribute("mobile", mobile);
		//redis中的验证码KEY
		String verifyCodeKey = MyConstants.MOBILE_VERIFY_CODE_KEY.concat(IPUtils.getIntenetIP(request));
		//redis中的验证码值
		String sendVerifyCode = redisService.get(verifyCodeKey);
		if (String.valueOf(receiveVerifyCode).equals(sendVerifyCode)) {
			//校验成功后将验证码缓存清空
			redisService.del(verifyCodeKey); 
			Long customerId = this.getCustomerId();
			try {
				int res = customerService.updateCustomerPassword(mobile, password);
				if (res > 0) {
					request.setAttribute(PublicStatus.RESULT_CODE, 1);
					request.setAttribute(PublicStatus.RESULT_MSG,  "重置密码成功");
				} else {
					request.setAttribute(PublicStatus.RESULT_CODE, 0);
					request.setAttribute(PublicStatus.RESULT_MSG,  "重置密码失败");
				}
			} catch (Exception e) {
				request.setAttribute(PublicStatus.RESULT_CODE, 0);
				request.setAttribute(PublicStatus.RESULT_MSG,  "重置密码失败");
				logger.error("重置密码失败:{}", e);
			}
		} else {
			model.addAttribute("receiveVerifyCode", receiveVerifyCode);
			request.setAttribute(PublicStatus.RESULT_CODE, 0);
			request.setAttribute(PublicStatus.RESULT_MSG,  "验证码错误");
		}
		return "/wx/my/setting/resetPwd";
	}
	
	/**
	 * 保存QQ
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月23日 下午7:27:36
	 */
	@RequestMapping("updateQQNumber")
	public String updateQQNumber(HttpServletRequest request, String qqNumber) {
		Long customerId = this.getCustomerId();
		if (StringUtil.isNotEmpty(qqNumber)) {
			try {
				CustomerEntity customerEntity = new CustomerEntity();
				customerEntity.setId(customerId);
				customerEntity.setQqNumber(qqNumber);
				customerService.updateCustomer(customerEntity);
				return "redirect:/wx/my/setting";
			} catch (Exception e) {
				request.setAttribute(PublicStatus.RESULT_CODE, 0);
				request.setAttribute(PublicStatus.RESULT_MSG,  "保存QQ失败");
				logger.error("保存QQ失败:{}", e);
			}
		} else {
			request.setAttribute(PublicStatus.RESULT_CODE, 0);
			request.setAttribute(PublicStatus.RESULT_MSG, "参数不正确");
		}
		request.setAttribute("qqNumber", qqNumber);
		return "/wx/my/setting/setQQ";
	}
	
	/**
	 * 保存Email
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月23日 下午7:27:36
	 */
	@RequestMapping("updateEmail")
	public String updateEmail(HttpServletRequest request, String email) {
		Long customerId = this.getCustomerId();
		if (StringUtil.isNotEmpty(email)) {
			try {
				CustomerEntity customerEntity = new CustomerEntity();
				customerEntity.setId(customerId);
				customerEntity.setEmail(email);
				customerService.updateCustomer(customerEntity);
				return "redirect:/wx/my/setting";
			} catch (Exception e) {
				request.setAttribute(PublicStatus.RESULT_CODE, 0);
				request.setAttribute(PublicStatus.RESULT_MSG,  "保存Email失败");
				logger.error("保存Email失败:{}", e);
			}
		} else {
			request.setAttribute(PublicStatus.RESULT_CODE, 0);
			request.setAttribute(PublicStatus.RESULT_MSG, "参数不正确");
		}
		request.setAttribute("email", email);
		return "/wx/my/setting/setMail";
	}
	
	/**
	 * 将微信上传的图片（阿里云图片地址）保存到数据库
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年11月23日 上午10:31:58
	 */
	@RequestMapping("saveUploadPicture")
	@ResponseBody
	public Map<String, Object> saveUploadPicture(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String filePath = request.getParameter("filePath");
			String customerId = request.getParameter("customerId");
			if (StringUtil.isNotEmpty(customerId) && StringUtil.isNotEmpty(filePath)) {
				CustomerEntity customerEntity = new CustomerEntity();
				customerEntity.setId(Long.parseLong(customerId));
				customerEntity.setHeadImage(filePath);
				customerService.updateCustomer(customerEntity);
				
				resultMap.put(PublicStatus.RESULT_CODE, 1);
				resultMap.put(PublicStatus.RESULT_MSG,  "保存图片成功");
			} else {
				resultMap.put(PublicStatus.RESULT_CODE, 0);
				resultMap.put(PublicStatus.RESULT_MSG,  "参数不能为空");
			}
		} catch (Exception e) {
			resultMap.put(PublicStatus.RESULT_CODE, 0);
			resultMap.put(PublicStatus.RESULT_MSG,  "保存图片失败");
			logger.error("将微信上传的图片（阿里云图片地址）保存到数据库失败:{}", e);
		}
		
		return resultMap;
	}
}
